﻿Imports System.Xml
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Public Class clsEOC
#Region "xml Updates/Signature"
    Public Structure sUpdates
        Public Structure sTeam
            Public TeamName As String
            Public TeamID As String
            Public Rank As String
            Public Users_Active As String
            Public Users As String
            Public Change_Rank_24h As String
            Public Change_Rank_7days As String
            Public Points_24h_Avg As String
            Public Points_Update As String
            Public Points_Today As String
            Public Points_Week As String
            Public Points As String
            Public WUs As String
        End Structure
        Public Structure sUser
            Public User_Name As String
            Public UserID As String
            Public Team_Rank As String
            Public Overall_Rank As String
            Public Change_Rank_24h As String
            Public Change_Rank_7days As String
            Public Points_24h_Avg As String
            Public Points_Update As String
            Public Points_Today As String
            Public Points_Week As String
            Public Points As String
            Public WUs As String
        End Structure
        Public Structure sUpdateStatus
            Private _Last_Update As DateTime
            Public ReadOnly Property strDT() As String
                Get
                    Return _strDT
                End Get
            End Property
            Public WriteOnly Property Last_Update() As String
                Set(ByVal value As String)
                    _strDT = value
                    Dim iYear As Int16 = CInt(Mid(strDT, 1, 4))
                    Dim iMonth As Int16 = CInt(Mid(strDT, 5, 2))
                    Dim iDay As Int16 = CInt(Mid(strDT, 7, 2))
                    Dim iHours As Int16 = CInt(Mid(strDT, 9, 2))
                    Dim iMinutes As Int16 = CInt(Mid(strDT, 11, 2))
                    Dim iSeconds As Int16 = CInt(Mid(strDT, 13, 2))
                    _Last_Update = New DateTime(iYear, iMonth, iDay, iHours, iMinutes, iSeconds, DateTimeKind.Unspecified)
                End Set
            End Property
            Public ReadOnly Property Last_Update_CST() As DateTime
                Get
                    Dim iYear As Int16 = CInt(Mid(strDT, 1, 4))
                    Dim iMonth As Int16 = CInt(Mid(strDT, 5, 2))
                    Dim iDay As Int16 = CInt(Mid(strDT, 7, 2))
                    Dim iHours As Int16 = CInt(Mid(strDT, 9, 2))
                    Dim iMinutes As Int16 = CInt(Mid(strDT, 11, 2))
                    Dim iSeconds As Int16 = CInt(Mid(strDT, 13, 2))
                    Last_Update = New DateTime(iYear, iMonth, iDay, iHours, iMinutes, iSeconds, DateTimeKind.Unspecified)
                    Return _Last_Update
                End Get
            End Property
            'Only use converting properties with .net 3.5       -  darnit Central Daylight Time is not a known timezone on my pc, and I think lot's more. I need utc
            Public ReadOnly Property Last_Update_UTC() As DateTime
                Get
                    Try
                        Dim dtUTC As DateTime = TimeZoneInfo.ConvertTime(_Last_Update, System.TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time"), TimeZoneInfo.Utc)
                        Return dtUTC
                    Catch ex As Exception
                        'Log to window
                        Return DateTime.MinValue
                    End Try
                End Get
            End Property
            Public ReadOnly Property Last_Update_LocalTime() As DateTime
                Get
                    Try
                        Dim dtLocal As DateTime = TimeZoneInfo.ConvertTime(_Last_Update, System.TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time"), TimeZoneInfo.Local)
                        Return dtLocal
                    Catch ex As Exception
                        'Log to window
                        Return DateTime.MinValue
                    End Try
                End Get
            End Property
            Public ReadOnly Property LastUpdateString() As String
                Get
                    Try
                        Dim strRet As String = Last_Update_LocalTime.ToShortDateString & " " & Last_Update_LocalTime.ToShortTimeString & " (" & Update_Status & ")"
                        Return strRet
                    Catch ex As Exception
                        LogWindow.WriteError("clsEOC, LastupdateString", Err, ex.Message)
                        Return vbNullString
                    End Try
                End Get
            End Property
            Private _strDT As String
            Public Update_Status As String
        End Structure
        Public Team As sTeam
        Public User As sUser
        Public UpdateStatus As sUpdateStatus
        Private _IsEmpty As Boolean
        Public Property IsEmpty() As Boolean
            Get
                Return _IsEmpty
            End Get
            Set(ByVal value As Boolean)
                _IsEmpty = value
            End Set
        End Property
    End Structure
    Private _bFilled As Boolean
    Private _Updates(0 To 0) As sUpdates
    Private _UserName As String, _TeamNumber As String
    Private _Path As String
    Private _ImageUrl As String = "http://folding.extremeoverclocking.com/sigs/sigimage.php?un="
    Private _bHasImage As Boolean = False
    Private _bImageRecent As Boolean = False
    Private _SigFile As String
    Private WithEvents _tForceUpdate As New System.Timers.Timer
    Private Sub _tForceUpdate_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _tForceUpdate.Elapsed
        Try
            If ShouldRefresh Then ReadWebXml()
        Catch ex As Exception
            LogWindow.WriteError("clsEOC, tForceUpdate.elapsed", Err)
        End Try
    End Sub
    Public ReadOnly Property bImageRecent() As Boolean
        Get
            Return _bImageRecent
        End Get
    End Property
    Public ReadOnly Property bHasImage() As Boolean
        Get
            Return _bHasImage
        End Get
    End Property
    Public ReadOnly Property fileSignatureImage() As String
        Get
            Return _SigFile
        End Get
    End Property
    Public ReadOnly Property LastUpdate() As sUpdates
        Get
            Try
                Return _Updates(_Updates.GetUpperBound(0))
            Catch ex As Exception
                LogWindow.WriteError("clsEOC, LastUpdate", Err, ex.Message)
                Dim eUpdate As New sUpdates
                eUpdate.IsEmpty = True
                Return eUpdate
            End Try
        End Get
    End Property
    Public ReadOnly Property WU_Update() As String
        Get
            Try
                If Not Filled Then Return vbNullString
                If _Updates.GetUpperBound(0) = 0 Then Return vbNullString
                Dim iNew As Double = CDbl(_Updates(_Updates.GetUpperBound(0)).User.WUs)
                Dim iOld As Double = CDbl(_Updates(_Updates.GetUpperBound(0) - 1).User.WUs)
                Return CStr(iNew - iOld)
            Catch ex As Exception
                LogWindow.WriteError("clsEOC, sUpdates, WU_Update", Err, ex.Message)
                Return vbNullString
            End Try
        End Get
    End Property
    Public ReadOnly Property ShouldRefresh() As Boolean
        Get
            Try
                If Not _bFilled Then Return True
                If DateTime.Now.Subtract(_Updates(_Updates.GetUpperBound(0)).UpdateStatus.Last_Update_LocalTime).TotalHours > 3 Then
                    Return True
                Else
                    Return False
                End If
            Catch ex As Exception
                LogWindow.WriteError("clsEOC, ShouldRefresh", Err, ex.Message)
                Return True
            End Try
        End Get
    End Property
    Public ReadOnly Property Filled() As Boolean
        Get
            Return _bFilled
        End Get
    End Property
    Public Function RefreshEOC() As Boolean
        Try
            If Not ShouldRefresh Then Return False
            Return (ReadWebXml() And LoadSigImage())
        Catch ex As Exception
            'Log to window
            Return False
        End Try
    End Function
    Private Function LoadSigImage() As Boolean
        Try
            If My.Computer.FileSystem.FileExists(_SigFile) Then
                Dim fInf As New FileInfo(_SigFile)
                If DateTime.Now.Subtract(fInf.LastWriteTime).TotalHours > 3 Then
                    If modMAIN.EOC_Net_Failure <> DateTime.MinValue Then
                        If DateTime.Now.Subtract(modMAIN.EOC_Net_Failure).TotalMinutes < 15 Then
                            LogWindow.WriteLog("EOC signature image outdated but last failure less then 15 minutes ago, aborting update and using old image")
                            _bHasImage = True
                            _bImageRecent = False
                            Return True
                        End If
                        Try
                            If Not My.Computer.Network.Ping("extremeoverclocking.com") Then
                                modMAIN.EOC_Net_Failure = DateTime.Now
                                LogWindow.WriteError("clsEOC, LoadSigImage", Err, "Could not ping site, waiting 15 minutes before retry.")
                            Else
                                modMAIN.EOC_Net_Failure = DateTime.MinValue
                                If My.Computer.FileSystem.FileExists(_SigFile) Then
                                    My.Computer.FileSystem.DeleteFile(_SigFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.DoNothing)
                                    WaitMS(50)
                                End If
                                My.Computer.Network.DownloadFile(_ImageUrl, _SigFile)
                                _bHasImage = True
                                _bImageRecent = True
                                Return True
                            End If
                        Catch ex As Exception
                            LogWindow.WriteError("clsEOC, LoadSigImage", Err, "Could not ping site, waiting 15 minutes before retry.")
                            modMAIN.EOC_Net_Failure = DateTime.Now
                            _bHasImage = True
                            _bImageRecent = False
                            Return True
                        End Try
                    ElseIf DateTime.Now.Subtract(modMAIN.EOC_Net_Failure).TotalMinutes > 15 Then
                        Try
                            LogWindow.WriteLog("EOC signature image outdated, trying to refresh.")
                            If Not My.Computer.Network.Ping("extremeoverclocking.com") Then
                                LogWindow.WriteError("clsEOC, LoadSigImage", Err, "Could not ping site, waiting 15 minutes before retry.")
                                modMAIN.EOC_Net_Failure = DateTime.Now
                                _bHasImage = True
                                _bImageRecent = False
                                Return True
                            Else
                                modMAIN.EOC_Net_Failure = DateTime.MinValue
                                If My.Computer.FileSystem.FileExists(_SigFile) Then
                                    My.Computer.FileSystem.DeleteFile(_SigFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.DoNothing)
                                    WaitMS(50)
                                End If
                                My.Computer.Network.DownloadFile(_ImageUrl, _SigFile)
                                _bHasImage = True
                                _bImageRecent = True
                                Return True
                            End If
                        Catch ex As Exception
                            LogWindow.WriteError("clsEOC, LoadSigImage", Err)
                            modMAIN.EOC_Net_Failure = DateTime.Now
                            _bHasImage = True
                            _bImageRecent = False
                            Return True
                        End Try
                    End If
                Else
                    _bHasImage = True
                    _bImageRecent = True
                    Return True
                End If
            Else
                Try
                    LogWindow.WriteLog("Trying to fetch EOC signature image.")
                    If Not modMAIN.EOC_Net_Failure = DateTime.MinValue Then
                        If DateTime.Now.Subtract(modMAIN.EOC_Net_Failure).TotalMinutes < 15 Then
                            LogWindow.WriteLog("Aborting signature image fetching, last failure less then 15 minutes ago")
                            _bHasImage = False
                            _bImageRecent = False
                            Return False
                        End If
                    End If
                    If Not My.Computer.Network.Ping("extremeoverclocking.com") Then
                        modMAIN.EOC_Net_Failure = DateTime.Now
                        LogWindow.WriteError("clsEOC, LoadSigImage", Err, "Could not ping site, waiting 15 minutes before retry.")
                        _bHasImage = False
                        _bImageRecent = False
                        Return False
                    Else
                        modMAIN.EOC_Net_Failure = DateTime.MinValue
                        If My.Computer.FileSystem.FileExists(_SigFile) Then
                            My.Computer.FileSystem.DeleteFile(_SigFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.DoNothing)
                            WaitMS(50)
                        End If
                        My.Computer.Network.DownloadFile(_ImageUrl, _SigFile)
                        _bHasImage = True
                        _bImageRecent = True
                        Return True
                    End If
                Catch ex As Exception
                    modMAIN.EOC_Net_Failure = DateTime.Now
                    LogWindow.WriteError("clsEOC, LoadSigImage", Err)
                    _bHasImage = False
                    _bImageRecent = False
                    Return False
                End Try
            End If
        Catch ex As Exception
            LogWindow.WriteError("clsEOC, LoadSigImage", Err)
            _bHasImage = False
            _bImageRecent = False
            Return False
        End Try
    End Function
    Private Function LoadLocalXML() As Boolean
        Try
            'Backup updates
            Dim bUpdates(0 To _Updates.GetUpperBound(0)) As sUpdates
            Array.Copy(_Updates, bUpdates, _Updates.GetUpperBound(0))
            ReDim _Updates(0 To 0)
            _Updates(0).IsEmpty = True
            If Not My.Computer.FileSystem.DirectoryExists(_Path) Then Return False
            Dim fNames = My.Computer.FileSystem.GetFiles(_Path, FileIO.SearchOption.SearchTopLevelOnly, "*.xml")
            Dim mySort As New clsSort, alFiles As New ArrayList
            For Each Fname In fNames
                alFiles.Add(New FileInfo(Fname))
            Next
            alFiles.Sort(mySort)
            If Not mySettings.EocLimit = clsSettings.eEocLimit.None Then
                For xInt As Int16 = 0 To alFiles.Count - 1
                    Dim fInf As FileInfo = CType(alFiles(xInt), FileInfo)
                    Select Case mySettings.EocLimit
                        Case clsSettings.eEocLimit.Minimal
                            If xInt > alFiles.Count - 2 Then
                                My.Computer.FileSystem.DeleteFile(fInf.FullName)
                                alFiles.RemoveAt(xInt)
                            End If
                        Case clsSettings.eEocLimit.OneDay
                            If DateTime.Now.Subtract(fInf.CreationTime).TotalDays > 1 Then
                                My.Computer.FileSystem.DeleteFile(fInf.FullName)
                                alFiles.RemoveAt(xInt)
                            End If
                        Case clsSettings.eEocLimit.OneWeek
                            If DateTime.Now.Subtract(fInf.CreationTime).TotalDays > 7 Then
                                My.Computer.FileSystem.DeleteFile(fInf.FullName)
                                alFiles.RemoveAt(xInt)
                            End If
                        Case clsSettings.eEocLimit.OneMonth
                            If DateTime.Now.Subtract(fInf.CreationTime).TotalDays > 30 Then
                                My.Computer.FileSystem.DeleteFile(fInf.FullName)
                                alFiles.RemoveAt(xInt)
                            End If
                    End Select
                Next
            End If
            Dim bOnce As Boolean = True
            For Each fInfo As FileInfo In alFiles
                If bOnce Then
                    bOnce = False
                Else
                    ReDim Preserve _Updates(0 To _Updates.GetUpperBound(0) + 1)
                End If
                Using xReader As XmlReader = XmlReader.Create(fInfo.FullName)
                    With _Updates(_Updates.GetUpperBound(0))
                        xReader.ReadToFollowing("Team_Name")
                        .Team.TeamName = xReader.ReadElementString
                        .Team.TeamID = xReader.ReadElementString
                        .Team.Rank = xReader.ReadElementString
                        .Team.Users_Active = xReader.ReadElementString
                        .Team.Users = xReader.ReadElementString
                        .Team.Change_Rank_24h = xReader.ReadElementString
                        .Team.Change_Rank_7days = xReader.ReadElementString
                        .Team.Points_24h_Avg = xReader.ReadElementString
                        .Team.Points_Update = xReader.ReadElementString
                        .Team.Points_Today = xReader.ReadElementString
                        .Team.Points_Week = xReader.ReadElementString
                        .Team.Points = xReader.ReadElementString
                        .Team.WUs = xReader.ReadElementString
                        xReader.ReadToFollowing("User_Name")
                        .User.User_Name = xReader.ReadElementString
                        .User.UserID = xReader.ReadElementString
                        .User.Team_Rank = xReader.ReadElementString
                        .User.Overall_Rank = xReader.ReadElementString
                        .User.Change_Rank_24h = xReader.ReadElementString
                        .User.Change_Rank_7days = xReader.ReadElementString
                        .User.Points_24h_Avg = xReader.ReadElementString
                        .User.Points_Update = xReader.ReadElementString
                        .User.Points_Today = xReader.ReadElementString
                        .User.Points_Week = xReader.ReadElementString
                        .User.Points = xReader.ReadElementString
                        .User.WUs = xReader.ReadElementString
                        xReader.ReadToFollowing("Last_Update")
                        .UpdateStatus.Last_Update = xReader.ReadElementString
                        .UpdateStatus.Update_Status = xReader.ReadElementString
                        .IsEmpty = False
                    End With
                End Using
            Next
            If _Updates.GetUpperBound(0) >= 0 And _Updates(_Updates.GetUpperBound(0)).IsEmpty = False Then
                _bFilled = True
            Else
                _bFilled = False
            End If
            Return True
        Catch ex As Exception
            LogWindow.WriteError("Loadlocal xml, clsEOC", Err, ex.Message)
            Return False
        End Try
    End Function
    Private Function ReadWebXml(Optional ByVal UserName As String = "", Optional ByVal TeamNumber As String = "") As Boolean
        Try
            If modMAIN.EOC_Net_Failure <> DateTime.MinValue Then
                If DateTime.Now.Subtract(modMAIN.EOC_Net_Failure).TotalMinutes < 15 Then
                    LogWindow.WriteLog("EOC xml feed outdated, but last failure less then 15 minutes ago, aborting update")
                    Return False
                End If
            End If
            Try
                If Not My.Computer.Network.Ping("extremeoverclocking.com") Then
                    LogWindow.WriteLog("Could not read xml feed from EOC, site seems down")
                    Return False
                Else
                    modMAIN.EOC_Net_Failure = DateTime.MinValue
                End If
            Catch ex As Exception
                LogWindow.WriteError("Trying to update EOC xml feed, ping error.", Err)
                Return False
            End Try

            If UserName = "" Then UserName = _UserName
            If TeamNumber = "" Then TeamNumber = _TeamNumber
            Dim newUpdate As New sUpdates
            Dim xSettings As XmlReaderSettings = New XmlReaderSettings()
            xSettings.IgnoreComments = True
            xSettings.IgnoreProcessingInstructions = True
            xSettings.IgnoreWhitespace = True
            Dim xResolver As XmlUrlResolver = New XmlUrlResolver()
            xResolver.Credentials = System.Net.CredentialCache.DefaultCredentials
            ' Set the reader settings object to use the resolver.
            xSettings.XmlResolver = xResolver
            Using xReader As XmlReader = XmlReader.Create("http://folding.extremeoverclocking.com/xml/user_summary.php?un=" & UserName & "&t=" & TeamNumber, xSettings)
                xReader.ReadToFollowing("Team_Name")
                With newUpdate
                    .Team.TeamName = xReader.ReadElementString
                    .Team.TeamID = xReader.ReadElementString
                    .Team.Rank = xReader.ReadElementString
                    .Team.Users_Active = xReader.ReadElementString
                    .Team.Users = xReader.ReadElementString
                    .Team.Change_Rank_24h = xReader.ReadElementString
                    .Team.Change_Rank_7days = xReader.ReadElementString
                    .Team.Points_24h_Avg = xReader.ReadElementString
                    .Team.Points_Update = xReader.ReadElementString
                    .Team.Points_Today = xReader.ReadElementString
                    .Team.Points_Week = xReader.ReadElementString
                    .Team.Points = xReader.ReadElementString
                    .Team.WUs = xReader.ReadElementString
                    xReader.ReadToFollowing("User_Name")
                    .User.User_Name = xReader.ReadElementString
                    .User.UserID = xReader.ReadElementString
                    .User.Team_Rank = xReader.ReadElementString
                    .User.Overall_Rank = xReader.ReadElementString
                    .User.Change_Rank_24h = xReader.ReadElementString
                    .User.Change_Rank_7days = xReader.ReadElementString
                    .User.Points_24h_Avg = xReader.ReadElementString
                    .User.Points_Update = xReader.ReadElementString
                    .User.Points_Today = xReader.ReadElementString
                    .User.Points_Week = xReader.ReadElementString
                    .User.Points = xReader.ReadElementString
                    .User.WUs = xReader.ReadElementString
                    xReader.ReadToFollowing("Last_Update")
                    .UpdateStatus.Last_Update = xReader.ReadElementString
                    .UpdateStatus.Update_Status = xReader.ReadElementString
                    .IsEmpty = False
                End With
            End Using
            xSettings = Nothing
            xResolver = Nothing

            Dim bHas As Boolean = False
            Try
                If _Updates(0).UpdateStatus.Last_Update_LocalTime = Nothing Then
                    ReDim _Updates(0 To 0)
                End If
            Catch ex As Exception
                ReDim _Updates(0 To 0)
            Finally

            End Try

            For xInt As Int16 = 0 To _Updates.Count - 1
                If _Updates(xInt).UpdateStatus.Last_Update_UTC = newUpdate.UpdateStatus.Last_Update_UTC Then
                    bHas = True
                    Exit For
                End If
            Next

            If Not bHas Then
                If Not _Updates(0).UpdateStatus.Last_Update_UTC = DateTime.MinValue Then ReDim Preserve _Updates(0 To _Updates.GetUpperBound(0) + 1)
                _Updates(_Updates.GetUpperBound(0)) = newUpdate
            End If

            If _Updates.GetUpperBound(0) > 0 And _Updates(_Updates.GetUpperBound(0)).IsEmpty = False Then
                _bFilled = True
            End If

            If Not newUpdate.User.WUs = "" Then
                'Save to local XML
                SaveLocal()
                Return True
            Else
                Return False
            End If
        Catch ex As System.Net.WebException
            LogWindow.WriteError("clsEOC, readwebxml, webException", Err, ex.Message)
        Catch ex As Exception
            LogWindow.WriteError("clsEOC, readwebxml", Err, ex.Message)
            Return False
        End Try
    End Function
    Private Function SaveLocal() As Boolean
        Try
            Dim iSkipIndex As Int16 = -1
            For xInt As Int16 = 0 To _Updates.GetUpperBound(0)
                Dim Update As sUpdates = _Updates(xInt)
                If Not mySettings.EocLimit = clsSettings.eEocLimit.None Then
                    Select Case mySettings.EocLimit
                        Case clsSettings.eEocLimit.Minimal
                            If xInt < _Updates.GetUpperBound(0) Then GoTo Skip
                        Case clsSettings.eEocLimit.OneDay
                            If Update.UpdateStatus.Last_Update_LocalTime < DateTime.Now.Subtract(TimeSpan.FromDays(1)) Then
                                iSkipIndex = xInt
                                GoTo Skip
                            End If
                        Case clsSettings.eEocLimit.OneWeek
                            If Update.UpdateStatus.Last_Update_LocalTime < DateTime.Now.Subtract(TimeSpan.FromDays(7)) Then
                                iSkipIndex = xInt
                                GoTo Skip
                            End If
                        Case clsSettings.eEocLimit.OneMonth
                            If Update.UpdateStatus.Last_Update_LocalTime < DateTime.Now.Subtract(TimeSpan.FromDays(30)) Then
                                iSkipIndex = xInt
                                GoTo Skip
                            End If
                    End Select
                End If
                If Not Update.IsEmpty Then
                    Dim fName As String = dPath & "\EOC\" & _UserName & "(" & _TeamNumber & ")" & "\" & Update.UpdateStatus.strDT & ".xml"
                    If Not My.Computer.FileSystem.DirectoryExists(dPath & "\EOC\" & _UserName & "(" & _TeamNumber & ")" & "\") Then My.Computer.FileSystem.CreateDirectory(dPath & "\EOC\" & _UserName & "(" & _TeamNumber & ")" & "\")
                    If Not My.Computer.FileSystem.FileExists(fName) Then
                        Using xWriter As XmlWriter = XmlWriter.Create(fName)
                            With xWriter
                                .WriteStartDocument()
                                .WriteStartElement("EOC_Feed")
                                .WriteStartElement("Team")
                                .WriteElementString("Team_Name", Update.Team.TeamName)
                                .WriteElementString("TeamID", Update.Team.TeamID)
                                .WriteElementString("Rank", Update.Team.Rank)
                                .WriteElementString("Users_Active", Update.Team.Users_Active)
                                .WriteElementString("Users", Update.Team.Users)
                                .WriteElementString("Change_Rank_24h", Update.Team.Change_Rank_24h)
                                .WriteElementString("Change_Rank_7days", Update.Team.Change_Rank_7days)
                                .WriteElementString("Points_25h_Avg", Update.Team.Points_24h_Avg)
                                .WriteElementString("Points_Update", Update.Team.Points_Update)
                                .WriteElementString("Points_Today", Update.Team.Points_Today)
                                .WriteElementString("Points_Week", Update.Team.Points_Week)
                                .WriteElementString("Points", Update.Team.Points)
                                .WriteElementString("WUs", Update.Team.WUs)
                                .WriteEndElement()
                                .WriteStartElement("User")
                                .WriteElementString("User_Name", Update.User.User_Name)
                                .WriteElementString("UserID", Update.User.UserID)
                                .WriteElementString("Team_Rank", Update.User.Team_Rank)
                                .WriteElementString("Overall_Rank", Update.User.Overall_Rank)
                                .WriteElementString("Change_Rank_24h", Update.User.Change_Rank_24h)
                                .WriteElementString("Change_Rank_7daÿs", Update.User.Change_Rank_7days)
                                .WriteElementString("Points_24hr_Avg", Update.User.Points_24h_Avg)
                                .WriteElementString("Points_Update", Update.User.Points_Update)
                                .WriteElementString("Points_Today", Update.User.Points_Today)
                                .WriteElementString("Points_Week", Update.User.Points_Week)
                                .WriteElementString("Points", Update.User.Points)
                                .WriteElementString("WUs", Update.User.WUs)
                                .WriteEndElement()
                                .WriteStartElement("Status")
                                .WriteElementString("Last_Update", Update.UpdateStatus.strDT)
                                .WriteElementString("Update_Status", Update.UpdateStatus.Update_Status)
                                .WriteEndElement()
                                .WriteEndElement()
                                .WriteEndDocument()
                            End With
                        End Using
                    End If
                End If
Skip:
            Next
            If Not iSkipIndex = -1 Then
                ReDim Preserve _Updates(0 To iSkipIndex)
            End If
            Return True
        Catch ex As Exception
            LogWindow.WriteError("clsEOC, readwebxml", Err, ex.Message)
            Return False
        End Try
    End Function
    Private Class clsSort
        Implements IComparer
        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
            ' make it return this in descending order (newest first) 
            Return DateTime.Compare(DirectCast(x, FileInfo).CreationTime, DirectCast(y, FileInfo).CreationTime)
        End Function
    End Class
    Public Sub New(ByVal UserName As String, ByVal TeamNumber As String)
        Try
            With _tForceUpdate
                .AutoReset = True
                .Interval = TimeSpan.FromHours(2).TotalMilliseconds
            End With
            _Updates(0) = New sUpdates
            _UserName = UserName
            _TeamNumber = TeamNumber
            _Path = dPath & "\EOC\" & _UserName & "(" & _TeamNumber & ")" & "\"
            _ImageUrl &= _UserName & "&t=" & TeamNumber
            _SigFile = _Path & "Signature.gif"
            _fileWUs = _Path & "UploadedWUs.bin"
            LoadSigImage()
            LoadLocalXML()
            If ShouldRefresh Then
                Dim tRead As New Threading.Thread(AddressOf ReadWebXml)
                tRead.Start()
            End If
            _tForceUpdate.Enabled = True
        Catch ex As Exception
            LogWindow.WriteError("clsEOC, sub New(" & _UserName & "," & _TeamNumber & ")", Err, ex.Message)
            _bFilled = False
        End Try
    End Sub
#End Region
#Region "Uploaded workunits"
    'Need to move this to the stats class after I fixed it being unable to get the corestatus message when the queue moves to another slot
    Private binSerializer As New BinaryFormatter, _fileWUs As String
    <Serializable()> _
    Public Structure sWUs
        Public Points As String
        Public CEntry As clsQueue.Entry
        Public dtUpload As DateTime
        Public ClientIndex As Int16
    End Structure
    Private alWUs As New ArrayList
    Private wuSort As New clsWUSort
    Public Sub AddWu(ByVal Points As String, ByVal dtUpload As DateTime, ByVal ClientIndex As Int16, ByVal QSlot As clsQueue.Entry)
        Try
            Dim nWu As New sWUs
            With nWu
                .Points = Points
                .dtUpload = dtUpload
                .ClientIndex = ClientIndex
                .CEntry = QSlot
            End With
            If alWUs.Contains(nWu) Then Exit Sub
            alWUs.Add(nWu)
        Catch ex As Exception
            LogWindow.WriteError("clsEOC, Uploaded work units, AddWu", Err, ex.Message)
        End Try
    End Sub
    Public ReadOnly Property PointsInUpdate(ByVal ClientIndex) As String
        Get
            Try
                'Get wu's uploaded before last update.localtime
                alWUs.Sort(wuSort)
                Dim dblPoints As Double = 0
                For xInt As Int16 = 0 To alWUs.Count - 1
                    If CType(alWUs(xInt), sWUs).ClientIndex = ClientIndex Then
                        If CType(alWUs(xInt), sWUs).dtUpload < LastUpdate.UpdateStatus.Last_Update_LocalTime Then
                            dblPoints += CDbl(CType(alWUs(xInt), sWUs).Points)
                        End If
                    End If
                Next
                Math.Round(dblPoints, 4)
                Dim strPoints As String = dblPoints.ToString
                If InStr(strPoints, ",") <> 0 Then
                    Dim iDigits As Int16 = strPoints.Length - strPoints.LastIndexOf(",")
                    For iAddDigits As Int16 = 4 To iDigits Step -1
                        strPoints &= "0"
                    Next
                Else
                    strPoints &= ",0000"
                End If
                Return strPoints
            Catch ex As Exception
                LogWindow.WriteError("clsEOC, PointsInUpdate", Err)
                Return "0,0000"
            End Try
        End Get
    End Property
    Private Class clsWUSort
        Implements IComparer
        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
            ' make it return this in descending order (newest first) 
            Return DateTime.Compare(DirectCast(x, clsEOC.sWUs).dtUpload, DirectCast(y, clsEOC.sWUs).dtUpload)
        End Function
    End Class
#End Region
End Class
